package com.seuic.hnjiningposapp.hnapps.base;

import android.content.Context;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.orhanobut.logger.Logger;
import com.seuic.constants.EmvConstants;
import com.seuic.hnjiningposapp.R;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.AutomaticOperationPopup;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.ErrorPopup;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.ReadCardPopup;
import com.seuic.hnjiningposapp.hnapps.util.AppManager;
import com.seuic.hnjiningposapp.hnapps.util.HttpUtils;
import com.seuic.hnjiningposapp.hnapps.util.PinPad;
import com.seuic.hnjiningposapp.hnapps.util.SAXUnionFiled55Utils;
import com.seuic.hnjiningposapp.hnapps.util.Utils;
import com.seuic.posdsdk.pos_func.PosCallbacks;
import com.seuic.posdsdk.pos_func.PosFuncs;
import com.socks.library.KLog;

import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * 基类
 *
 * @author rainking
 */
public abstract class BaseActivity extends AppCompatActivity implements IActivity {

    /**
     * 通用的TAG
     */
    protected final String TAG = this.getClass().getSimpleName();
    private Unbinder mBinder;

    /**
     * 错误统一弹窗
     */
    private BasePopupView ErrorPopupView;

    /**
     * 进度条统一处理
     */
    private LoadingPopupView loadingPopup;

    /**
     * 读卡统一处理
     */
    private BasePopupView readCardPopupView;


    /**
     * 卡片类型
     */
    private String CardType;
    /**
     * 卡号
     */
    private String bindNum;
    /**
     * 二磁信息
     */
    private String track2Data;
    /**
     * 三磁信息
     */
    private String track3Data;

    private String pin;
    /**
     * 不同的操作类型
     */
    private AutomaticOperationPopup automaticOperationPopup;
    private BasePopupView automaticOperationPopupView;


    protected BaseActivity() {


    }

    public void showLoadingPopup(String msg, Runnable runnable) {
        loadingPopup = (LoadingPopupView) new XPopup.Builder(this)
                .dismissOnTouchOutside(false)
                .dismissOnBackPressed(false)
                .asLoading(msg);
        loadingPopup.show();
        loadingPopup.post(runnable);
    }

    public void dismissLoadingPopup() {
        if (loadingPopup != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    loadingPopup.dismiss();

                }
            });
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK，同时没有重复
            finish();
            return true;

        }

        return super.onKeyDown(keyCode, event);
    }


    public void showErrorPopup(String msg) {
        KLog.e(msg);
        setTitleText( "错误提示");
        ErrorPopup errorPopup = new ErrorPopup(BaseActivity.this, new ErrorPopup.OnFinishCallbacked() {
            @Override
            public void finished() {
                BaseActivity.this.finish();
            }
        });
        errorPopup.setMsg(msg);
        ErrorPopupView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(errorPopup);
        ErrorPopupView.show();
    }


    public void showErrorPopup(String msg, ErrorPopup.OnFinishCallbacked onFinishCallback) {
        setTitleText("错误提示" );
        ErrorPopup errorPopup = new ErrorPopup(BaseActivity.this, onFinishCallback);
        ErrorPopupView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(errorPopup);
        errorPopup.setMsg(msg);
        ErrorPopupView.show();
    }

    public void dismissErrorPopup() {
        ErrorPopupView.dismiss();
    }

    public void showReadCardPopup() {
        ReadCardPopup readCardPop = new ReadCardPopup(this);
        readCardPopupView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .moveUpToKeyboard(false)
                .dismissOnTouchOutside(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(readCardPop);
        readCardPopupView.show();
    }

    public void dismissReadCardPopup() {
        readCardPopupView.dismiss();
    }

    /**
     * 验证信息
     *
     * @param todo_type 不同的操作类型
     */
    public void showMakeHint(String todo_type) {
        if (automaticOperationPopup != null) {
            automaticOperationPopup = null;
        }
        if (automaticOperationPopupView != null) {
            automaticOperationPopupView = null;
        }
        automaticOperationPopup = new AutomaticOperationPopup(
                this, todo_type);
        automaticOperationPopupView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(automaticOperationPopup);
        automaticOperationPopupView.show();
    }


    public void dismissshowMakeHint() {
        automaticOperationPopupView.dismiss();
    }

    /**
     * 读取卡
     *
     * @param readCardListener 回调
     */
    public void readCard(HttpUtils.BaseReadCardListener readCardListener) {
        KLog.e("读取卡", "readCardTest: 开始读卡");
        showReadCardPopup();
        ThreadUtils.getIoPool().execute(() -> {
            PosFuncs.getInstace().cardReaderConfig(true, true, true);
            PosFuncs.getInstace().emvSimpleFlow(new PosCallbacks.EmvTransStartCallbacks() {
                @Override
                public void onDetectCard(String type) {
                    KLog.e("读取卡_卡号类型", type);
                    CardType = type;
                }

                @Override
                public void onConfirmCardInfo(String pan) {
                    KLog.e("读取卡_卡号", pan);
                    bindNum = pan;
                    SPStaticUtils.put("CardNo-bindNum", pan);
                    PosFuncs.getInstace().emvConfirmCardInfo(EmvConstants.CONFIRM_OK);
                }

                @Override
                public void onOlinePinEntered(String enc, boolean isNoPin) {
                    //得到密码明文
                    KLog.e("得到密码明文");
                    KLog.e(enc + "encencenc");

                    try {
                        SPStaticUtils.put("cleartextPasswords", PinPad.getPin(bindNum, enc));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onSuccess(Bundle data) {
                    KLog.e("FEILD_55" + data.getString(EmvConstants.FEILD_55));
                    //如果是磁条卡，就获取二磁信息、上传给银行接口
                    // IC Card    MAG Card    RF Card
                    if (CardType.equals("MAG Card")) {
                        track2Data = data.getString(EmvConstants.TRACK2);
                        track3Data = data.getString(EmvConstants.TRACK3);
                        KLog.e("读取卡_MAG Card" + "MAG Card");
                    } else {
                        KLog.e(EmvConstants.FEILD_55 + "F55");
                        KLog.e("读取卡_IC Card" + "IC Card");
                        track2Data = Utils.formatField57(Utils.getValueFromIccData("57", data.getString(EmvConstants.FEILD_55)));
                        String s_number = Utils.getValueFromIccData("5f34", data.getString(EmvConstants.FEILD_55));
                        SPStaticUtils.put("CardSeqNo", "0" + s_number);
                        String[] tags =
                                {
                                        "9F26", "9F27", "9F10", "9F37", "9F36", "95",
                                        "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03", "9F33", "9F34", "9F35",
                                        "9F1E", "84", "9F09", "9F41"
                                };
                        String Field55 = Utils.getField55(tags, data.getString(EmvConstants.FEILD_55));
                        String l55 = SAXUnionFiled55Utils.returnFile55("9F2608EB1338CA7977676F9F2701809F101307330103A02000040A0100000010005F97DECC9F37049F3E97939F3602015D950508A004E0009A032005119C01009F02060000000001005F2A02015682027C009F1A0201569F03060000000000009F3303E069C89F34034203009F3501229F1E0800000000000000008408A0000003330101019F090202009F41040000000057136231160001010483492D29122208472470100F9B02E800500A50424F432044454249545A0A6231160001010483492F5F24032912315F340101");
                        KLog.e(l55 + "Field55");
                        SPStaticUtils.put("Field55", l55);
                        KLog.e("读取卡_ic Card", s_number + "s_numbers_number读取卡");
                        if (readCardListener != null) {
                            readCardListener.onSuccess(bindNum, track2Data);
                        }
                        readCardPopupView.dismiss();
                    }
                }

                @Override
                public void onFailed(String error) {
                    KLog.e("读取卡_error", error);
                    if (readCardListener != null) {
                        readCardListener.onError("读卡失败，请插入卡");
                    }
                }
            });
        });
    }


    public void tradeWithCards(HttpUtils.BaseReadCardTwListener baseReadCardTwListener) {

        KLog.e("读取卡", "tradeWithCards: 开始读卡");
        showReadCardPopup();
        PinPad.initPinPad(PosFuncs.getInstace());
        new Thread() {
            @Override
            public void run() {
                PosFuncs.getInstace().cardReaderConfig(true, true, true);
                PosFuncs.getInstace().emvTransStart(new PosCallbacks.EmvTransStartCallbacks() {
                    String cipassword;


                    @Override
                    public void onDetectCard(String type) {
                        KLog.e("读取卡_卡号类型" + type);
                        CardType = type;
                    }

                    @Override
                    public void onConfirmCardInfo(final String pan) {
                        KLog.e("读取卡_卡号", pan);
                        bindNum = pan;
                        SPStaticUtils.put("CardNo-bindNum", pan);
                        PosFuncs.getInstace().emvConfirmCardInfo(EmvConstants.CONFIRM_OK);

                    }

                    @Override
                    public void onOlinePinEntered(String enc, boolean is_no_pin) {
                        //得到密码明文

                        try {
                            String pw = PinPad.getPin(bindNum, enc);
                            SPStaticUtils.put("cleartextPasswords", pw);

                            cipassword = HttpUtils.getResult(pw, bindNum);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onSuccess(Bundle data) {
                        String channel = data.getString(EmvConstants.CHANNEL);
                        if (EmvConstants.CHANNEL_MAGCARD.equals(channel)) {

                        } else if (EmvConstants.CHANNEL_ICC.equals(channel)) {
                            track2Data = Utils.formatField57(Utils.getValueFromIccData("57", data.getString(EmvConstants.FEILD_55)));
                            String s_number = Utils.getValueFromIccData("5f34", data.getString(EmvConstants.FEILD_55));
                            SPStaticUtils.put("CardSeqNo", "0" + s_number);
                            String ac_type = data.getString(EmvConstants.AC_TYPE);
                            Logger.e("ac_type" + ac_type);
                            Logger.e("Ac Type: " + data.getString(EmvConstants.AC_TYPE) + "\n");
                            Logger.e("Field 55: " + data.getString(EmvConstants.FEILD_55) + "\n");
                            Log.e("55", data.getString(EmvConstants.FEILD_55));
                            String l55 = SAXUnionFiled55Utils.returnFile55(data.getString(EmvConstants.FEILD_55));

                            SPStaticUtils.put("Field55", l55);
                            if (EmvConstants.AC_TYPE_ARQC.equals(ac_type)) {
                                Bundle bundle = new Bundle();
                                bundle.putString(EmvConstants.RESPONSE_CODE, "3030");
                                PosFuncs.getInstace().emvOnlineResult(new PosCallbacks.EmvOnlineResultCallbacks() {
                                    @Override
                                    public void onSuccess(Bundle data) {


                                    }

                                    @Override
                                    public void onFailed(String error) {

                                    }
                                }, bundle);
                            } else {

                            }
                        } else if (EmvConstants.CHANNEL_ICCL.equals(channel)) {

                        }
                        KLog.e(bindNum + "bindNum");
                        KLog.e(cipassword + "cipassword");

                        baseReadCardTwListener.onSuccess(bindNum, track2Data, cipassword);
                        readCardPopupView.dismiss();
                    }

                    @Override
                    public void onFailed(String error) {
                        KLog.e("读取卡_error", error);
                        KLog.e("读取卡_error", error);
                        if (baseReadCardTwListener != null) {
                            baseReadCardTwListener.onError("读卡失败，请插入卡");
                        }
                    }
                }, 0, 0);
            }
        }.start();
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        AppManager.getAppManager().addActivity(this);
        try {
            //从实现类获取布局
            int layoutResourceId = initView(savedInstanceState);
            //如果initView返回0,框架则不会调用setContentView(),当然也不会 Bind ButterKnife
            if (layoutResourceId != 0) {
                setContentView(layoutResourceId);
                //绑定到butterKnife
                mBinder = ButterKnife.bind(this);
                //初始化数据
                initData(savedInstanceState);
                initEvent(savedInstanceState);
            }
        } catch (Exception e) {
            ToastUtils.showLong("页面数据异常");
            e.printStackTrace();
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        //收回软键盘
        KeyboardUtils.hideSoftInput(this);
    }

    /**
     * 返回时隐藏打开的输入法
     */
    private void backHideSoftImm() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        View currentFocus = this.getCurrentFocus();
        if (currentFocus != null) {
            IBinder windowToken = currentFocus.getWindowToken();
            assert imm != null;
            imm.hideSoftInputFromWindow(windowToken, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 设置界面上的返回按钮
     *
     * @param backId 布局ID
     */
    protected void setBackBtClick(@IdRes int backId) {
        findViewById(backId).setOnClickListener(view -> finish());
    }

    /**
     * 设置界面标题
     */
    protected void setTitleText(String text) {
        dismissLoadingPopup();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ((TextView) findViewById(R.id.base_title_text)).setText(text);

            }
        });
    }


    public void exitLogin() {
        AppManager.getAppManager().finishAllActivity();
        AppUtils.exitApp();
    }

    /**
     * Destroy时，执行各种注销置空操作
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注解解绑
        if (mBinder != null && mBinder != Unbinder.EMPTY) {
            mBinder.unbind();
        }
        this.mBinder = null;
        AppManager.getAppManager().removeActivity(this);
    }
}
